package Patron;

import java.net.HttpURLConnection;
import java.sql.Time;
import java.util.GregorianCalendar;
import java.util.Map;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.BindingProvider;

import org.jboss.ws.annotation.EndpointConfig;
import org.jboss.ws.core.StubExt;

import edu.ipfw.fitness.MembershipDurationType;
import edu.ipfw.fitness.MembershipType;
import edu.ipfw.fitness.PatronType;
import edu.ipfw.services.patron.Patron;
import edu.ipfw.services.patron.PatronService;
import edu.ipfw.services.patron.SecurePatron;
import edu.ipfw.services.patron.SecurePatronService;

public class SecurePatronClient {
	
	//	1.	Create a Java project named cs590-project2-test.
	//	2.	Configure the client to use the fitness-center security domain.
	//	3.	Create a Java application class named SecurePatronClient.
	//	4.	Construct SecurePatron service calls to accomplish the following.
	//		a.	Configure the RequestContext with a username of ‘admin’ and a password of ‘ubertusker’.
	//		b.	Add a FACULTY Patron with an id of ‘9001234567’ and membership duration of SEMESTER. You may choose values for other required data.
	//		c.	Add a FACULTY Patron with an id of ‘9001234568’ and a membership duration of YEAR. You may choose values for other required data.
	//		d.	Add two Patron visits for Patron with id of ‘9001234567’. Make each duration 90 minutes. Use two different dates.
	//		e.	Checkin Patron with id of ‘9001234568’.
	//		f.	Checkout Patron with id of ‘9001234568’.
	//		g.	Renew FACULTY Patron with id of ‘9001234567’ and membership duration of YEAR.
	//	5.	Construct Patron calls to accomplish the following.
	//		a.	Configure the RequestContext with a username of ‘admin’ and a password of ‘ubertusker’.
	//		b.	Display each Patron.
	//		c.	Display total number of Patron visits between the earliest start date and latest end date you used when adding Patron visits/checking in.
	//		d.	Display total number of Patron visits for today.
	//		e.	Display average visit duration of Patron visits between the earliest start date and latest end date you used when adding Patron visits/checking in.
	//	6.	Configure the Patron RequestContext with a username of ‘staff1’ and a password of ‘tusker1’.
	//	7.	Repeat steps 5b-5e.
	//	8.	Configure the SecurePatron RequestContext with a username of ‘staff1’ and a password of ‘tusker1’.
	//	9.	Attempt to add a STUDENT Patron with an id of ‘9001111111’ and a membership duration of YEAR. You may choose values for other required data.
	//	10.	Configure the Patron RequestContext with a username of ‘hacker’ and a password of ‘nogood’.
	//	11.	Attempt to display Patron with id of ‘9001234567’.
	//	12.	Configure the SecurePatron RequestContext with a username of ‘hacker’ and a password of ‘nogood’.
	//	13.	Attempt to add a STUDENT Patron with an id of ‘9001111111’ and a membership duration of YEAR. You may choose values for other required data.
	public static void main(String[] args) 
	{
		//4.	Construct SecurePatron service calls to accomplish the following.
		SecurePatron sp = new SecurePatron();
		SecurePatronService spService = sp.getSecurePatronServiceImplPort();
		
		System.out.println("***************START OF FIRST SECURE PATRON TEST***************");
		
		Map<String,Object> requestContext = ((BindingProvider) spService).getRequestContext();
		
		//4.a.	Configure the RequestContext with a username of ‘admin’ and a password of ‘ubertusker’.
		String userid = "admin";
		String password = "ubertusker";
		
		requestContext.put(BindingProvider.USERNAME_PROPERTY, userid);
		requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
		
		((StubExt) spService).setConfigName("Standard WSSecurity Client");
		try {
			//4.b.	Add a FACULTY Patron with an id of ‘9001234567’ and membership duration of SEMESTER. You may choose values for other required data.
			spService.register("9001234567", "User1", "Test", "test.user1@test.com", MembershipType.ALUMNI, MembershipDurationType.SEMESTER);
			
			//4.c.	Add a FACULTY Patron with an id of ‘9001234568’ and a membership duration of YEAR. You may choose values for other required data.
			spService.register("9001234568", "User2", "Test", "test.user2@test.com", MembershipType.ALUMNI, MembershipDurationType.YEAR);
			
			//4.d.	Add two Patron visits for Patron with id of ‘9001234567’. Make each duration 90 minutes. Use two different dates.
			GregorianCalendar firstVisitStart = new GregorianCalendar();
			GregorianCalendar firstVisitEnd= new GregorianCalendar();;
			GregorianCalendar secondVisitStart= new GregorianCalendar();;
			GregorianCalendar secondVisitEnd= new GregorianCalendar();;
			
			firstVisitStart.set(2011,4,18,4,0);
			firstVisitEnd.set(2011,4,18,5,30);
			secondVisitStart.set(2011,4,19,6,0);
			secondVisitEnd.set(2011,4,19,7,30);
			
			spService.addVisit("9001234567", convertGregorianToXMLGregorian(firstVisitStart), convertGregorianToXMLGregorian(firstVisitEnd));
			spService.addVisit("9001234567", convertGregorianToXMLGregorian(secondVisitStart), convertGregorianToXMLGregorian(secondVisitEnd));
			
			//4.e.	Checkin Patron with id of ‘9001234568’.
			spService.checkIn("9001234568");
			
			// Add some time between check-in and check-out
			Thread.sleep(1000);
			
			//4.f.	Checkout Patron with id of ‘9001234568’.
			spService.checkOut("9001234568");
			
			//4.g.	Renew FACULTY Patron with id of ‘9001234567’ and membership duration of YEAR
			// NOT WORKING!!!!
			//port.renew("9001234567", MembershipDurationType.YEAR);
			
			System.out.println();
			System.out.println("***************END OF FIRST SECURE PATRON TEST***************");
			System.out.println();
			System.out.println();
		} catch (Exception e) {
		        String message = e.getMessage();
		        //e.printStackTrace();
		        System.out.println(message);
		        if (message.contains(""+HttpURLConnection.HTTP_UNAUTHORIZED))
		        	System.out.println("User failed authentication.");
		        else
		        	System.out.println("User failed authorization.");
		}
		
		//5.	Construct Patron calls to accomplish the following.
		Patron p = new Patron();
		PatronService pService = p.getPatronServiceImplPort();
		
		System.out.println("***************START OF FIRST PATRON TEST***************");
		requestContext = ((BindingProvider) pService).getRequestContext();
		
		//5.a.	Configure the RequestContext with a username of ‘admin’ and a password of ‘ubertusker’.
		userid = "admin";
		password = "ubertusker";
		System.out.println("Using UserID=" + userid + " and Password=" + password);
		System.out.println();
		
		requestContext.put(BindingProvider.USERNAME_PROPERTY, userid);
		requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
		
		//((StubExt) pService).setConfigName("Standard WSSecurity Client");
		try {
			//5.b.	Display each Patron.
			String id = "9001234567";
			PatronType patron = pService.getMember(id);

			System.out.println("Displaying Member " + id + " Information:");
			System.out.println(
					"\n\tPatron ID: " + patron.getId() +
					"\n\tLast Name: " + patron.getLastName() +
					"\n\tFirst Name: "+ patron.getFirstName() + 
					"\n\tEmail: " + patron.getEmail() +
					"\n\tMembership Type: " + patron.getMembershipType().toString() +
					"\n\tMembership Duration: " + patron.getMembershipDuration().toString() +
					"\n\tExpiration Date: " + patron.getExpirationDate() +
					"\n\tLast Check In Date: " + patron.getLastCheckInDate() +
					"\n\tIs checked in? " + patron.isCheckedIn());
			
			System.out.println();
			
			id = "9001234568";
			patron = pService.getMember(id);

			System.out.println("Displaying Member " + id + " Information:");
			System.out.println(
					"\n\tPatron ID: " + patron.getId() +
					"\n\tLast Name: " + patron.getLastName() +
					"\n\tFirst Name: "+ patron.getFirstName() + 
					"\n\tEmail: " + patron.getEmail() +
					"\n\tMembership Type: " + patron.getMembershipType().toString() +
					"\n\tMembership Duration: " + patron.getMembershipDuration().toString() +
					"\n\tExpiration Date: " + patron.getExpirationDate() +
					"\n\tLast Check In Date: " + patron.getLastCheckInDate() +
					"\n\tIs checked in? " + patron.isCheckedIn());
			
			//5.c.	Display total number of Patron visits between the earliest start date and latest end date you used when adding Patron visits/checking in.
			GregorianCalendar earliestStartDate = new GregorianCalendar();
			GregorianCalendar latestEndDate = new GregorianCalendar();
			
			earliestStartDate.set(2011,3,18,3,0);
			latestEndDate.set(2011,6,20,8,30);
			
			int totalVisits = pService.getVisitsForDateRange(convertGregorianToXMLGregorian(earliestStartDate), convertGregorianToXMLGregorian(latestEndDate),null);
			
			System.out.println();
			System.out.println("Total number of Patron visits between " + convertGregorianToXMLGregorian(earliestStartDate) + " and " + convertGregorianToXMLGregorian(latestEndDate) + ": " + totalVisits);
			System.out.println();
			
			//5.d.	Display total number of Patron visits for today.
			System.out.println("Total number of Patron visits today: " + pService.getVisitsForToday(null));
			System.out.println();
			
			//5.e.	Display average visit duration of Patron visits between the earliest start date and latest end date you used when adding Patron visits/checking in.
			long avgTotalVisitDuration = pService.getAvgVisitDuration(null);
			Time duration = new Time(avgTotalVisitDuration);
			System.out.println("Display average visit duration of Patron visits: " + duration);
			
			System.out.println();
			System.out.println("***************END OF FIRST PATRON TEST***************");
			System.out.println();
			System.out.println();
		} catch (Exception e) {
		        String message = e.getMessage();
		        //e.printStackTrace();
		        System.out.println(message);
		        if (message.contains(""+HttpURLConnection.HTTP_UNAUTHORIZED))
		        	System.out.println("User failed authentication.");
		        else
		        	System.out.println("User failed authorization.");
		}
		
		System.out.println("***************START OF SECOND PATRON TEST***************");
		requestContext = ((BindingProvider) pService).getRequestContext();
		
		//6.	Configure the Patron RequestContext with a username of ‘staff1’ and a password of ‘tusker1’.
		userid = "staff1";
		password = "tusker1";
		System.out.println("Using UserID=" + userid + " and Password=" + password);
		System.out.println();
		
		requestContext.put(BindingProvider.USERNAME_PROPERTY, userid);
		requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
		
		//((StubExt) pService).setConfigName("Standard WSSecurity Client");
		
		//7.	Repeat steps 5b-5e.
		try
		{
			//7.b.	Display each Patron.
			String id = "9001234567";
			PatronType patron = pService.getMember(id);

			System.out.println("Displaying Member " + id + " Information:");
			System.out.println(
					"\n\tPatron ID: " + patron.getId() +
					"\n\tLast Name: " + patron.getLastName() +
					"\n\tFirst Name: "+ patron.getFirstName() + 
					"\n\tEmail: " + patron.getEmail() +
					"\n\tMembership Type: " + patron.getMembershipType().toString() +
					"\n\tMembership Duration: " + patron.getMembershipDuration().toString() +
					"\n\tExpiration Date: " + patron.getExpirationDate() +
					"\n\tLast Check In Date: " + patron.getLastCheckInDate() +
					"\n\tIs checked in? " + patron.isCheckedIn());
			
			System.out.println();
			
			id = "9001234568";
			patron = pService.getMember(id);

			System.out.println("Displaying Member " + id + " Information:");
			System.out.println(
					"\n\tPatron ID: " + patron.getId() +
					"\n\tLast Name: " + patron.getLastName() +
					"\n\tFirst Name: "+ patron.getFirstName() + 
					"\n\tEmail: " + patron.getEmail() +
					"\n\tMembership Type: " + patron.getMembershipType().toString() +
					"\n\tMembership Duration: " + patron.getMembershipDuration().toString() +
					"\n\tExpiration Date: " + patron.getExpirationDate() +
					"\n\tLast Check In Date: " + patron.getLastCheckInDate() +
					"\n\tIs checked in? " + patron.isCheckedIn());

			//7.c.	Display total number of Patron visits between the earliest start date and latest end date you used when adding Patron visits/checking in.
			GregorianCalendar earliestStartDate = new GregorianCalendar();
			GregorianCalendar latestEndDate = new GregorianCalendar();
			
			earliestStartDate.set(2011,3,18,3,0);
			latestEndDate.set(2011,6,20,8,30);
			
			int totalVisits = pService.getVisitsForDateRange(convertGregorianToXMLGregorian(earliestStartDate), convertGregorianToXMLGregorian(latestEndDate),null);
			
			System.out.println();
			System.out.println("Total number of Patron visits between " + convertGregorianToXMLGregorian(earliestStartDate) + " and " + convertGregorianToXMLGregorian(latestEndDate) + ": " + totalVisits);
			System.out.println();
			
			//7.d.	Display total number of Patron visits for today.
			System.out.println("Total number of Patron visits today: " + pService.getVisitsForToday(null));
			System.out.println();
			
			//7.e.	Display average visit duration of Patron visits between the earliest start date and latest end date you used when adding Patron visits/checking in.
			long avgTotalVisitDuration = pService.getAvgVisitDuration(null);
			Time duration = new Time(avgTotalVisitDuration);
			System.out.println("Display average visit duration of Patron visits: " + duration);
			
			System.out.println();
			System.out.println("***************END OF SECOND PATRON TEST***************");
			System.out.println();
			System.out.println();	
		} 
		catch (Exception e) 
		{
	        String message = e.getMessage();
	        //e.printStackTrace();
	        System.out.println(message);
	        if (message.contains(""+HttpURLConnection.HTTP_UNAUTHORIZED))
	        	System.out.println("User failed authentication.");
	        else
	        	System.out.println("User failed authorization.");
		}
		
		System.out.println("***************START OF SECOND SECURE PATRON TEST***************");
		requestContext = ((BindingProvider) spService).getRequestContext();
		
		//8.	Configure the SecurePatron RequestContext with a username of ‘staff1’ and a password of ‘tusker1’.
		userid = "staff1";
		password = "tusker1";
		System.out.println("Using UserID=" + userid + " and Password=" + password);
		System.out.println();
		
		requestContext.put(BindingProvider.USERNAME_PROPERTY, userid);
		requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
		
		//((StubExt) spService).setConfigName("Standard WSSecurity Client");
		
		try
		{
			//9.	Attempt to add a STUDENT Patron with an id of ‘9001111111’ and a membership duration of YEAR. You may choose values for other required data.
			spService.register("9001111111", "User3", "Test", "test.user3@test.com", MembershipType.ALUMNI, MembershipDurationType.YEAR);
		} 
		catch (Exception e) 
		{
	        String message = e.getMessage();
	        //e.printStackTrace();
	        System.out.println(message);
	        if (message.contains(""+HttpURLConnection.HTTP_UNAUTHORIZED))
	        	System.out.println("User failed authentication.");
	        else
	        	System.out.println("User failed authorization.");
		}
		
		System.out.println();
		System.out.println("***************END OF SECOND SECURE PATRON TEST***************");
		System.out.println();
		System.out.println();
		
		System.out.println("***************START OF THIRD PATRON TEST***************");
		requestContext = ((BindingProvider) pService).getRequestContext();
		
		//10.	Configure the Patron RequestContext with a username of ‘hacker’ and a password of ‘nogood’.
		userid = "hacker";
		password = "nogood";
		System.out.println("Using UserID=" + userid + " and Password=" + password);
		System.out.println();
		
		requestContext.put(BindingProvider.USERNAME_PROPERTY, userid);
		requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
		
		//((StubExt) pService).setConfigName("Standard WSSecurity Client");
		
		try
		{
			//11.	Attempt to display Patron with id of ‘9001234567’.
			String id = "9001234567";
			PatronType patron = pService.getMember(id);

			System.out.println("Displaying Member " + id + " Information:");
			System.out.println(
					"\n\tPatron ID: " + patron.getId() +
					"\n\tLast Name: " + patron.getLastName() +
					"\n\tFirst Name: "+ patron.getFirstName() + 
					"\n\tEmail: " + patron.getEmail() +
					"\n\tMembership Type: " + patron.getMembershipType().toString() +
					"\n\tMembership Duration: " + patron.getMembershipDuration().toString() +
					"\n\tExpiration Date: " + patron.getExpirationDate() +
					"\n\tLast Check In Date: " + patron.getLastCheckInDate() +
					"\n\tIs checked in? " + patron.isCheckedIn());
			
			System.out.println();
		} 
		catch (Exception e) 
		{
	        String message = e.getMessage();
	        //e.printStackTrace();
	        System.out.println(message);
	        if (message.contains(""+HttpURLConnection.HTTP_UNAUTHORIZED))
	        	System.out.println("User failed authentication.");
	        else
	        	System.out.println("User failed authorization.");
		}
		
		System.out.println();
		System.out.println("***************END OF THIRD PATRON TEST***************");
		System.out.println();
		System.out.println();
		
		System.out.println("***************START OF THIRD SECURE PATRON TEST***************");
		requestContext = ((BindingProvider) spService).getRequestContext();
		
		//12.	Configure the SecurePatron RequestContext with a username of ‘hacker’ and a password of ‘nogood’.
		userid = "hacker";
		password = "nogood";
		System.out.println("Using UserID=" + userid + " and Password=" + password);
		System.out.println();
		
		requestContext.put(BindingProvider.USERNAME_PROPERTY, userid);
		requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
		
		//((StubExt) spService).setConfigName("Standard WSSecurity Client");
		
		try
		{
			//13.	Attempt to add a STUDENT Patron with an id of ‘9001111111’ and a membership duration of YEAR. You may choose values for other required data.
			spService.register("9001111111", "User4", "Test", "test.user4@test.com", MembershipType.STUDENT, MembershipDurationType.YEAR);
		} 
		catch (Exception e) 
		{
	        String message = e.getMessage();
	        //e.printStackTrace();
	        System.out.println(message);
	        if (message.contains(""+HttpURLConnection.HTTP_UNAUTHORIZED))
	        	System.out.println("User failed authentication.");
	        else
	        	System.out.println("User failed authorization.");
		}
		
		System.out.println();
		System.out.println("***************END OF THIRD SECURE PATRON TEST***************");
		System.out.println();
		System.out.println();
		
		System.exit(0);
	}
	
	private static XMLGregorianCalendar convertGregorianToXMLGregorian(GregorianCalendar cal) throws DatatypeConfigurationException {
		XMLGregorianCalendar dtf = null;
		dtf = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
		return dtf;
	}

}